﻿using System;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Rigidbody _body;
    public float Gravity = 10;
    protected bool IsGrounded;
    protected bool IsJumping;
    protected bool IsTurning;
    protected bool IsWalking;
    public float JumpForce = 25;
    public bool Jumps = false;
    public float MovementSpeed = 5;
    public float RotationSpeed = 90;

    public virtual void Start()
    {
        _body = GetComponent<Rigidbody>();
    }

    public virtual void FixedUpdate()
    {
        _body.AddForce(-Vector3.up*Gravity);
        IsGrounded = Physics.Raycast(transform.position, Vector3.down, .5f);
    }

    public virtual void Update()
    {
        var movement = Input.GetAxis("Vertical")*Time.deltaTime*MovementSpeed;
        var rotation = new Vector3();

        if (Input.GetAxis("Horizontal") > 0)
        {
            rotation.y = RotationSpeed*Time.deltaTime;
        }
        else if (Input.GetAxis("Horizontal") < 0)
        {
            rotation.y = -RotationSpeed*Time.deltaTime;
        }

        IsTurning = Math.Abs(rotation.y) > 0;

        transform.Rotate(rotation);
        var translation = Vector3.forward*movement;
        IsWalking = translation != Vector3.zero;
        transform.Translate(translation);
        if (IsJumping && IsGrounded)
            IsJumping = false;
        if (!Input.GetButton("Jump") || !IsGrounded || !Jumps || IsJumping) return;
        _body.AddForce(Vector3.up*JumpForce);
        IsJumping = true;
    }
}